package com.hhit.yb.compose_demo.viewModel

import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel

class ListViewModel(application: Application) : AndroidViewModel(application) {

    private val initialList = List(30) { index: Int ->
        Person(id = index, name = "Person: $index")
    }

    val people = mutableStateListOf<Person>().apply {
        addAll(initialList)
    }

    fun toggleSelection(index: Int) {
        val item = people[index]
        val isSelected = item.isSelected
        people[index] = item.copy(isSelected = !isSelected)
    }

    // 🔥 If you use list and call updateItemSelection whole list is recomposed
    // when you chance one item selection status
    var personList by mutableStateOf(initialList)

    // 🔥 setting new value to MutableState triggers recomposition for whole LazyColumn
    fun updateItemSelection(id: Int) {
        val newList = personList.map {
            if (it.id == id) {
                it.copy(isSelected = !it.isSelected)
            } else {
                it
            }
        }
        personList = newList
    }
}

data class Person(val id: Int, val name: String, val isSelected: Boolean = false)